// 使用切片，读取任意行数的文件
package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"strconv"
)

func readFileToFloats(fileName string) ([]float64, error) {
	var numbers []float64

	file, err := os.Open(fileName)
	if err != nil {
		return nil, err
	}

	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := scanner.Text()
		number, err := strconv.ParseFloat(line, 64)
		if err != nil {
			return nil, err
		}
		numbers = append(numbers, number)
	}

	err = file.Close()
	if err != nil {
		return nil, err
	}

	if scanner.Err() != nil {
		return nil, scanner.Err()
	}

	return numbers, nil
}

func main() {
	fileName := "p013_go_readfile_with_slice.txt"
	numbers, err := readFileToFloats(fileName)
	if err != nil {
		log.Fatal(err)
	}

	var sumv float64
	for _, number := range numbers {
		sumv += number
	}
	fmt.Println(numbers, sumv, len(numbers))
	fmt.Printf("average is = %.2f", sumv/float64(len(numbers)))
}
